package com.hb.trade.server.project.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hb.core.pojo.enums.FeeTypeEnum;
import com.hb.core.pojo.enums.PayStatusEnum;
import com.hb.core.pojo.parent.MPCommonEntity;
import com.hb.core.pojo.parent.PageResult;
import com.hb.core.pojo.project.file.dto.BidFileInfoDTO;
import com.hb.core.pojo.project.file.entity.BidFileInfo;
import com.hb.core.pojo.project.order.dto.UserOrderDTO;
import com.hb.core.pojo.project.order.dto.UserOrderGoodsDTO;
import com.hb.core.pojo.project.order.entity.UserOrder;
import com.hb.core.pojo.project.order.entity.UserOrderGoods;
import com.hb.core.pojo.project.order.mapper.UserOrderMapper;
import com.hb.core.pojo.project.order.vo.UserOrderExportListVO;
import com.hb.core.pojo.project.order.vo.UserOrderListVO;
import com.hb.core.pojo.project.section.dto.BidSectionDTO;
import com.hb.core.pojo.project.section.entity.BidSection;
import com.hb.trade.server.project.file.service.BidFileInfoService;
import com.hb.trade.server.project.order.service.UserOrderGoodsService;
import com.hb.trade.server.project.order.service.UserOrderService;
import com.hb.trade.server.project.section.service.raw.BidSectionService;
import org.fzzn.core.util.Enums;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单信息 服务实现类
 * </p>
 *
 * @author zhaojk
 * @since 2021-08-30
 */
@Service
public class UserOrderServiceImpl extends ServiceImpl<UserOrderMapper, UserOrder> implements UserOrderService {

    public final static String YES_DOWNLOAD = "已下载";
    public final static String NO_DOWNLOAD = "未下载";
    public final static String CONFIRM_DOWNLOAD = "确认下载";

    protected final BidSectionService bidSectionService;
    protected final BidFileInfoService bidFileInfoService;
    protected final UserOrderGoodsService userOrderGoodsService;

    public UserOrderServiceImpl(BidSectionService bidSectionService,
                                BidFileInfoService bidFileInfoService,
                                UserOrderGoodsService userOrderGoodsService) {
        this.bidSectionService = bidSectionService;
        this.bidFileInfoService = bidFileInfoService;
        this.userOrderGoodsService = userOrderGoodsService;
    }

    // 定义成员变量 不重复创建
    QueryWrapper<UserOrder> wrapper;
    QueryWrapper<UserOrderGoods> queryWrapper;


    /**
     * @param userOrder:
     * @Description: 投标人分页查询购买文件列表
     * @Author: zhongdl
     * @Date:2021/12/22 11:39
     * @return: {@link PageResult<   UserOrderDTO  > }
     **/
    @Override
    public PageResult<UserOrderDTO> pagePurchaseFile(UserOrderDTO userOrder) {
        Page<UserOrderDTO> pages = userOrder.pages();
        baseMapper.pagePurchaseFile(pages, userOrder);
        return PageResult.get(pages);
    }

    /**
     * 获取指定类型的费用
     *
     * @param sectionId 标段ID
     * @param feeType   费用类型
     * @return
     */
    @Override
    public BigDecimal getPrice(Long sectionId, FeeTypeEnum feeType) {
        BidSection section = bidSectionService.getById(sectionId);
        switch (feeType) {
            // 投标保证金
            case BID_PRO:
                return section.getBond();
            case PER_PRO:
                break;
            // 报名费
            case SIGN_UP:
                return section.getRegistrationFeeMoney();
            // 标书费
            case DOC_BOOK:
                Long fileId = section.getFileId();
                BidFileInfo fileInfo = bidFileInfoService.getById(fileId);
                if (fileInfo == null) {
                    return BigDecimal.ZERO;
                }
                return fileInfo.getDocumentSalePrice();
            // 系统使用费
            case SYS_USE:
                return section.getSystemUseFee();
            // 其他费用
            case OTHER:
            default:
                break;
        }
        return BigDecimal.ZERO;
    }

    /**
     * 获取指定类型的费用
     *
     * @param sectionId
     * @param feeType
     * @return
     */
    @Override
    public BigDecimal getPrice(Long sectionId, Integer feeType) {
        FeeTypeEnum feeTypeEnum = Enums.of(FeeTypeEnum.class, feeType);
        return getPrice(sectionId, feeTypeEnum);
    }

    /**
     * 获取指定类型的费用
     *
     * @param sectionId
     * @param feeType
     * @return
     */
    @Override
    public JSONObject getPriceInfo(Long sectionId, FeeTypeEnum feeType) {
        BidSection section = bidSectionService.getById(sectionId);
        JSONObject root = JSONUtil.createObj();
        switch (feeType) {
            // 报名费
            case SIGN_UP:
                root.putOpt("price", section.getRegistrationFeeMoney());
                return root;
            // 标书费
            case DOC_BOOK:
                Long fileId = section.getFileId();
                BidFileInfo fileInfo = bidFileInfoService.getById(fileId);
                root.putOpt("price", fileInfo.getDocumentSalePrice());

                BidFileInfoDTO bidFileInfoDTO = fileInfo.to(BidFileInfoDTO.class);
                root.putOpt("collectionIds", bidFileInfoDTO.getCollectionIds());


                return root;
            // 系统使用费
            case SYS_USE:
                root.putOpt("price", section.getSystemUseFee());
                root.putOpt("collectionId", section.getSysCollectionId());
                return root;
            // 其他费用
            case OTHER:
            default:
                break;
        }
        return root;
    }

    /**
     * 查询指定项目下的费用审核信息
     *
     * @param pages
     * @param sectionId
     * @param feeType
     * @return
     */
    @Override
    public Page<UserOrderDTO> feeManagers(Page<UserOrderDTO> pages, Long sectionId, Integer feeType) {
        return baseMapper.feeManagers(pages, sectionId, feeType);
    }

    /**
     * 费用管理统计列表
     *
     * @param sectionDTO
     * @return
     */
    @Override
    public PageResult<UserOrderDTO> feeStatistics(BidSectionDTO sectionDTO) {
        Page<UserOrderDTO> page = baseMapper.feeStatistics(sectionDTO.pages(), sectionDTO);
        Integer feeType = sectionDTO.getFeeType();
        for (UserOrderDTO record : page.getRecords()) {
            BigDecimal price = getPrice(record.getSectionId(), feeType);
            record.setPrice(price);
        }
        return PageResult.get(page);
    }

    /**
     * 查询订单详情
     * 带着商品列表信息
     *
     * @param orderDTOId
     * @return
     */
    @Override
    public UserOrderDTO getWholeInfo(Long orderDTOId) {
        UserOrder userOrder = getById(orderDTOId);

        QueryWrapper<UserOrderGoods> wrapper = UserOrderGoods.wrapper();
        wrapper.eq("order_id", userOrder.getId());
        List<UserOrderGoods> list = userOrderGoodsService.list(wrapper);

        UserOrderDTO to = userOrder.to(UserOrderDTO.class);
        to.setGoods(list);

        return to;
    }

    /**
     * 查询指定条件的订单列表
     *
     * @param goodsDTO
     * @return
     */
    @Override
    public PageResult<UserOrderDTO> pageWithGoodInfo(UserOrderGoodsDTO goodsDTO) {
        Page<UserOrderDTO> pages = goodsDTO.pages();
        baseMapper.selectOrderInfoByProjectId(pages, goodsDTO);
        return PageResult.get(pages);
    }

    /**
     * 查询指定投标人企业下的费用缴纳状态
     *
     * @param userOrderGoodsDTO#sectionId                标段ID
     * @param userOrderGoodsDTO#feeType                  费用类型
     * @param userOrderGoodsDTO#userOrderDTO#orderStatus 订单状态
     * @return
     */
    @Override
    public UserOrder queryUserOrder(UserOrderGoodsDTO userOrderGoodsDTO) {
        return baseMapper.queryUserOrder(userOrderGoodsDTO);
    }

    @Override
    public UserOrder getUserOrder(UserOrderDTO orderDTO) {
        Long id = orderDTO.getId();
        if (id == null) {
            QueryWrapper<UserOrder> wrapper = UserOrderDTO.wrapper();
            wrapper.eq("out_order_no", orderDTO.getOutOrderNo()).last("limit 1");
            UserOrder one = getOne(wrapper);
            if (one == null) {
                return null;
            }
            id = one.getId();
        }
        return getById(id);
    }

    @Override
    public List<UserOrderDTO> listUserOrderByFreeType(Long sectionId, Integer feeType, Long orgId) {
        return baseMapper.listUserOrderByFreeType(sectionId, feeType, orgId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<UserOrder> deleteOrderData(int minute) {
        // 查询出符合需要删除的订单
        wrapper = new QueryWrapper<>();
        wrapper.eq("order_status", PayStatusEnum.UN_PAY.getCode());
        Date currentDate = DateUtil.date();
        Date date = DateUtil.offsetMinute(currentDate, -minute);
        wrapper.le("create_time", date);

        List<UserOrder> willDelete = list(wrapper);
        if (CollUtil.isEmpty(willDelete)) {
            return CollUtil.list(false);
        }

        List<Long> orderIds = CollUtil.map(willDelete, MPCommonEntity::getId, true);

        // 删除订单
        removeByIds(orderIds);

        // 删除对应的商品信息
        queryWrapper = UserOrderGoods.wrapper();
        queryWrapper.in("order_id", orderIds);

        // 删除商品
        userOrderGoodsService.remove(queryWrapper);
        return willDelete;
    }

    /**
     * 查询成功订单列表
     *
     * @param userOrderDTO
     * @return PageResult<UserOrderListVO>
     * @author yuezheng
     * @date 2022/4/13 7:13 PM
     */
    @Override
    public PageResult<UserOrderListVO> selectOrderSuccessList(UserOrderDTO userOrderDTO) {
        Page<UserOrderDTO> pages = userOrderDTO.pages();
        baseMapper.selectOrderSuccessList(pages, userOrderDTO);
        return PageResult.get(pages).transferTo(UserOrderListVO.class);
    }

    /**
     * 统计本月成交额
     *
     * @param
     * @return java.math.BigDecimal
     * @author yuezheng
     * @date 2022/4/14 10:07 AM
     */
    @Override
    public BigDecimal countByOrderAmountToMonth(UserOrderDTO userOrderDTO) {
        return this.baseMapper.countByOrderAmountToMonth(userOrderDTO);
    }

    /**
     * 统计本月成交数
     *
     * @param
     * @return int
     * @author yuezheng
     * @date 2022/4/14 10:12 AM
     */
    @Override
    public Integer countOrderByToMonth(UserOrderDTO userOrderDTO) {
        return this.baseMapper.countOrderByToMonth(userOrderDTO);
    }

    /**
     * Excel导出
     *
     * @param
     * @return void
     * @author yuezheng
     * @date 2022/4/14 1:15 PM
     */
    @Override
    public List<UserOrderExportListVO> exportExcelList(UserOrderDTO userOrderDTO) {
        List<UserOrderExportListVO> userOrderExportList = this.baseMapper.selectExportOrderGoods(userOrderDTO);
        return userOrderExportList;
    }

    //
//    /**
//     * 分页查询订单管理页面
//     *
//     * @param userOrder
//     * @return
//     */
//    @Override
//    public Page<UserOrderDto> findOrderManagementList(UserOrderDto userOrder) {
//        Page<UserOrderDto> pages = userOrder.pages();
//        List<UserOrderDto> userOrderDtoList =  baseMapper.findOrderManagementList(pages,userOrder);
//        for (UserOrderDto userOrderDto : userOrderDtoList) {
//            userOrderDto.setOrderStatusName(Enums.nameOf(EnumPayStatus.class,userOrderDto.getOrderStatus()));
//            AbstractProject project = projectService.getByPrimaryKey(userOrderDto.getProjectId(), EnumBidWay.BID);
//            if (project == null){
//                continue;
//            }
//            userOrderDto.fillFileTypeName(project);
//            userOrderDto.setSellingUnitName(organizeExtendInfoService.findByOrgId(project.getBiddingOrganizeId()).getOrgName());
//        }
//        pages.setRecords(userOrderDtoList);
//        return pages;
//    }
//
//    @Override
//    public UserOrder findUserOrderByOrderNo(String orderNo) {
//        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
//        userOrderQueryWrapper.lambda().eq(UserOrder::getOrderNo,orderNo).last("limit 1");
//        return this.getOne(userOrderQueryWrapper);
//    }
//
//    /**
//     * 查询文件下载列表
//     *
//     * @param userOrder
//     * @return
//     */
//    @Override
//    public Page<UserOrderDto> findFileDownloadList(UserOrderDto userOrder) {
//        Page<UserOrderDto> pages = userOrder.pages();
//        List<UserOrderDto> userOrderDtoList =  baseMapper.findFileDownloadList(pages,userOrder);
//        for (UserOrderDto userOrderDto : userOrderDtoList) {
//            if (Enums.with(EnumLogic.NO,userOrderDto.getDownloadFlag())){
//                userOrderDto.setDownloadFlagName(CONFIRM_DOWNLOAD);
//            }
//        }
//        pages.setRecords(userOrderDtoList);
//        return pages;
//    }
//
//    @Override
//    public List<UserOrder> findTenderIdList(String sectionId) {
//        QueryWrapper<UserOrder> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(UserOrder::getSectionId,sectionId);
//        return this.list(queryWrapper);
//    }
}
